

public class BinarySearchTree {
    static class Treenode{
        public int val;
        public Treenode left;
        public Treenode right;

        public Treenode(int val) {
            this.val = val;
        }
    }

    public Treenode root;

    public void insert(int key){
        if(root == null){
            Treenode root = new Treenode(key);
            return;
        }

        Treenode parent = null;
        Treenode cur = root;
        Treenode node = new Treenode(key);
        while(cur != null){
            parent = cur;
            if(cur.val < key){
                cur = cur.right;
            }else if(cur.val > key){
                cur = cur.right;
            }else{
                return;
            }
        }

        if(parent.val > key){
            parent.left = node;
        }
        if(parent.val < key){
            parent.right = node;
        }
    }

    public Treenode search(int val){
        Treenode cur = root;
        while(cur != null){
            if(cur.val < val){
                cur = cur.right;
            }else if(cur.val > val){
                cur = cur.left;
            }else{
                return cur;
            }
        }
        return null;
    }

    public void remove(int val){
        Treenode cur = root;
        Treenode parent = null;
        while(cur != null){
            if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }else{
                removeTreenode(parent,cur);
                return;
            }
        }
    }

    public void removeTreenode(Treenode parent,Treenode cur){
        //cur的right为空的情况
        if(cur.right == null){
            if(cur == root){
                root = cur.left;
            }else {
                if(parent.left == cur){
                    parent.left = cur.left;
                }else if(parent.right == cur){
                    parent.right = cur.left;
                }
            }
        }else if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else{
                if(parent.left == cur){
                    parent.left = cur.right;
                }else if(parent.right == cur){
                    parent.right = cur.right;
                }
            }
        }else{
            //替换法：找到左树最右边或者右树最左边结点，与要删除结点val进行交换，再删除
            //那右树最左边举例
            Treenode tp = cur;
            Treenode t = tp.right;
            while(t != null){
                tp = t;
                t = t.left;
            }
            cur.val = t.val;//赋值
            if(tp.left == t){
                tp.left = t.right;
            }else{
                tp.right = t.right;
            }
        }
    }
}
